package top.tangyh.lamp.care.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.util.StringUtil;
import com.google.common.util.concurrent.AtomicDouble;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tangyh.basic.context.ContextUtil;
import top.tangyh.basic.exception.BizException;
import top.tangyh.basic.utils.DateUtils;
import top.tangyh.lamp.care.common.*;
import top.tangyh.lamp.care.entity.BExeYaoRevokeRecord;
import top.tangyh.lamp.care.entity.BHl7YzYaoPlan;
import top.tangyh.lamp.care.entity.BIoRecord;
import top.tangyh.lamp.care.mapper.BExeYaoEventMapper;
import top.tangyh.lamp.care.mapper.BExeYaoRevokeRecordMapper;
import top.tangyh.lamp.care.mapper.BHl7YzYaoPlanMapper;
import top.tangyh.lamp.care.mapper.BIoRecordMapper;
import top.tangyh.lamp.care.service.BExeYaoEventService;
import top.tangyh.basic.base.service.impl.SuperServiceImpl;
import top.tangyh.lamp.care.manager.BExeYaoEventManager;
import top.tangyh.lamp.care.entity.BExeYaoEvent;
import top.tangyh.lamp.care.service.BHl7YzYaoPlanService;
import top.tangyh.lamp.care.service.BIoRecordService;
import top.tangyh.lamp.care.vo.RevokeRecordYaoOutVO;
import top.tangyh.lamp.care.vo.query.*;
import top.tangyh.lamp.care.vo.result.*;
import top.tangyh.lamp.care.vo.save.BExeYaoEventSaveVO;
import top.tangyh.lamp.care.vo.save.ExeYaoEventInVO;
import top.tangyh.lamp.care.vo.save.ExeYaoInVO;
import top.tangyh.lamp.care.vo.save.YaoPlanInVO;
import top.tangyh.lamp.care.vo.update.BExeYaoEventUpdateVO;
import top.tangyh.lamp.care.vo.update.UpdateExeYaoInVO;
import top.tangyh.lamp.common.utils.*;
import top.tangyh.lamp.oauth.biz.OauthUserBiz;
import top.tangyh.lamp.oauth.vo.result.DefUserInfoResultVO;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import static top.tangyh.lamp.care.service.impl.BHl7YzYaoPlanServiceImpl.MED_DELIMITER;
import static top.tangyh.lamp.common.constant.CommonConstant.NO_NUMBER;
import static top.tangyh.lamp.common.constant.CommonConstant.YES_NUMBER;

/**
 * <p>
 * 业务实现类
 * 用药执行事件表
 * </p>
 *
 * @author zqb
 * @date 2024-07-26 10:31:52
 * @create [2024-07-26 10:31:52] [zqb] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(readOnly = true)
public class BExeYaoEventServiceImpl extends SuperServiceImpl<BExeYaoEventManager, Long, BExeYaoEvent> implements BExeYaoEventService {

    private final BExeYaoEventMapper bExeYaoEventMapper;

    private final BHl7YzYaoPlanMapper bHl7YzYaoPlanMapper;

    private final BHl7YzYaoPlanService bHl7YzYaoPlanService;

    public static final String USED = "used";

    private final OauthUserBiz oauthUserBiz;


    private final BIoRecordMapper bIoRecordMapper;


//    private final BIoRecordService bIoRecordService;

    private final BExeYaoRevokeRecordMapper bExeYaoRevokeRecordMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addEvent(ExeYaoEventInVO inVO) {
        Long eventTime = inVO.getEventTime();
        String groupIdStr = inVO.getGroupId();
        String planTime = DateUtil.formatDateTime(new Date(inVO.getPlanTime()));
        String groupId = groupIdStr + "-" + planTime;
        BExeYaoEvent addEventPO = new BExeYaoEvent();
        BeanUtil.copyProperties(inVO, addEventPO);
        addEventPO.setEventTime(PDateUtils.getDateTimeOfTimestamp(eventTime));
        addEventPO.setGroupId(groupId);


        //根据groupId获取事件列表
        List<BExeYaoEvent> eventPOList = bExeYaoEventMapper.selectListByGroupId(groupId);
        //不为空 则需要处理上次事件的结束时间和本次的速度差值
        if (CollectionUtil.isNotEmpty(eventPOList)) {
            List<BExeYaoEvent> sortedEventList = eventPOList.stream().sorted(Comparator.comparing(BExeYaoEvent::getEventTime)).collect(Collectors.toList());
            //上一次事件
            BExeYaoEvent lastEvent = CollectionUtil.getLast(sortedEventList);
            LocalDateTime lastEventTime = lastEvent.getEventTime();
            if (eventTime < PDateUtils.getTimestampOfDateTime(lastEventTime)) {
                //差值毫秒数
                long diffTime = PDateUtils.getTimestampOfDateTime(lastEventTime) - eventTime;
                //预留2分钟秒误差计算时间
                if (diffTime > IcuDateUtils.getMinuteMillisecond(2)) {
                    throw new BizException("当前事件时间不能早于上一个事件时间");
                }
                eventTime = eventTime + diffTime;
                addEventPO.setEventTime(PDateUtils.getDateTimeOfTimestamp((eventTime)));
            }
            //根据上一次的事件记录 修改上一次事件的结束时间
            BExeYaoEvent updatePo = new BExeYaoEvent();
            updatePo.setId(lastEvent.getId());
            updatePo.setEventOverTime(PDateUtils.getDateTimeOfTimestamp(eventTime));
            bExeYaoEventMapper.updateById(updatePo);

            //快推事件的值设定稍微特殊一些
            if (ExeYaoEventTypeEnum.FAST_PUSH.getEventType().equals(inVO.getEventType())) {
                addEventPO.setSpeed(inVO.getCurrentSpeed());
                addEventPO.setCurrentSpeed(lastEvent.getCurrentSpeed());
                //结束和完成事件的currentSpeed设置为0
            } else {
                if (ExeYaoEventTypeEnum.END.getEventType().equals(inVO.getEventType()) || ExeYaoEventTypeEnum.COMPLETE.getEventType().equals(inVO.getEventType())) {
                    addEventPO.setCurrentSpeed(0);
                }
                //计算当前速度的差值
                Integer lastCurrentSpeed = lastEvent.getCurrentSpeed();
                if (lastCurrentSpeed > inVO.getCurrentSpeed()) {
                    addEventPO.setSpeed(lastCurrentSpeed - inVO.getCurrentSpeed());
                } else {
                    addEventPO.setSpeed(inVO.getCurrentSpeed() - lastCurrentSpeed);
                }
            }
        } else {
            if (!ExeYaoEventTypeEnum.START.getEventType().equals(inVO.getEventType())) {
                throw new BizException("执行用药的第一个事件必须为开始事件类型");
            }
            //代表只有一个开始事件
            addEventPO.setSpeed(inVO.getCurrentSpeed());
        }
        //插入事件
        bExeYaoEventMapper.insert(addEventPO);

        //根据已有的事件列表 如果计算出总用量超过总量 则不让添加
        List<ExeYaoEventOutVO> eventOutList = bExeYaoEventMapper.selectListByGroupId(groupId).stream().sorted(Comparator.comparing(BExeYaoEvent::getEventTime)).map(ExeYaoEventOutVO::new).collect(Collectors.toList());
        List<BHl7YzYaoPlan> yaoPlanPOList = bHl7YzYaoPlanMapper.selectListByGroupId(groupId);

//        int totalCounts = yaoPlanPOList.stream().filter(yaoPlanPO -> yaoPlanPO.getYtCount() != null).mapToDouble(BHl7YzYaoPlan::getYtCount).sum();
        BigDecimal totalCounts = yaoPlanPOList.stream()
                // 将user对象的mongey取出来map为Bigdecimal
                .map(BHl7YzYaoPlan::getYtCount)
                // 使用reduce聚合函数,实现累加器
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        Map<String, Number> map = bHl7YzYaoPlanService.getTotalUsed(eventOutList, totalCounts.doubleValue());
        AtomicDouble used = (AtomicDouble) map.get(USED);
        double totalUsed = used.get();
        BigDecimal totalUsedB = new BigDecimal(Double.toString(totalUsed));
        totalCounts = totalCounts.add(new BigDecimal(5));
        //误差控制在5ml
//        if (totalUsed > (totalCounts + 5)) {
        if (totalUsedB.compareTo(totalCounts) == 1) {
            log.error("添加事件不合法,计算出已用量超过总量 total={} usedCount={}", totalCounts, totalUsed);
            throw new BizException("添加事件不合法,计算出已用量超过总量,请检查添加事件时间");
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEvent(Long id) {
        BExeYaoEvent eventPO = bExeYaoEventMapper.selectById(id);
        if (eventPO != null) {
            //需要把上一次事件的结束时间回退为null
            String groupId = eventPO.getGroupId();
            List<BExeYaoEvent> eventPOList = bExeYaoEventMapper.selectListByGroupId(groupId);
            List<BExeYaoEvent> list = eventPOList.stream().sorted(Comparator.comparing(BExeYaoEvent::getEventTime)).collect(Collectors.toList());
            if (list.size() >= 2) {
                BExeYaoEvent lastEvent = list.get(list.size() - 2);
                lastEvent.setEventOverTime(null);
                bExeYaoEventMapper.updateById(lastEvent);
            }
            //删除当前事件
            bExeYaoEventMapper.deleteById(id);
        }
    }


    @Override
    public List<ExeYaoOutVO> selectExeYaoListNoEventByQuery(ExeYaoQueryVO queryVO) {
        //需求变动 ： 根据分组id和时间分为一组用药，查询时间范围 为一天，后续需求文档会进行补充
        Long currentDate = queryVO.getCurrentDate();
        String hospitalNumber = queryVO.getHospitalNumber();
        if (currentDate == null || StrUtil.isBlank(hospitalNumber)) {
            throw new BizException("请输入当天时间戳和病人住院号参数");
        }
        Long workStartTime = queryVO.getWorkStartTime();
        Long workEndTime = queryVO.getWorkEndTime();
        if (workStartTime == null || workEndTime == null) {
            throw new BizException("请输入排班开始和结束时间戳");
        }
        String sortName = queryVO.getSortName();
        if (StrUtil.isBlank(sortName)) {
            throw new BizException("请输入排序字段");
        }
        //排班开始和结束时间
        String startDateStr = DateUtil.formatDateTime(DateUtil.date(workStartTime));
        String endDateStr = DateUtil.formatDateTime(DateUtil.date(workEndTime));

        List<BHl7YzYaoPlan> yaoPlanListByGroup =
                selectYaoList(null, startDateStr, endDateStr, hospitalNumber, 0, queryVO.getMedicationName(), queryVO.getRouteIdent(), queryVO.getConditionIdent(), null);

        if (CollectionUtil.isEmpty(yaoPlanListByGroup)) {
            return new ArrayList<>();
        }

        Map<String, List<BHl7YzYaoPlan>> groupMap = yaoPlanListByGroup.stream().collect(Collectors.groupingBy(v ->
                v.getGroupId() + "-" + PDateUtils.getLocalDateTimeToString(v.getPlanTime())));

        //组合成vo结果集
        List<ExeYaoOutVO> resultList = new ArrayList<>();
        //遍历是为了处理vo的属性值
        groupMap.forEach((groupIdPlanTime, yaoPlanPoList) -> {
            ExeYaoOutVO exeYaoOutVO = new ExeYaoOutVO();

            //主药在前
            List<String> medications = yaoPlanPoList.stream().sorted(Comparator.comparing(BHl7YzYaoPlan::getIsMaster).reversed()).map(BHl7YzYaoPlan::getMedication).collect(Collectors.toList());
            //药名由在同一组下的药名拼接组成
            String medicationName = String.join(MED_DELIMITER, medications);
            exeYaoOutVO.setMedicationName(medicationName);
            yaoPlanPoList.forEach(yxHl7YzYaoPlanPO -> {
                //根据主药组合vo
                if (yxHl7YzYaoPlanPO.getIsMaster().equals(YES_NUMBER)) {
                    BeanUtil.copyProperties(yxHl7YzYaoPlanPO, exeYaoOutVO);
                    exeYaoOutVO.setYaoExeTime(yxHl7YzYaoPlanPO.getExeTime());
                    exeYaoOutVO.setYaoStatus(yxHl7YzYaoPlanPO.getExeStatus());
                    exeYaoOutVO.setMasterId(yxHl7YzYaoPlanPO.getId());

                    exeYaoOutVO.setInputType(yxHl7YzYaoPlanPO.getInputType());
                    exeYaoOutVO.setRemarks(yxHl7YzYaoPlanPO.getRemarks());
                    exeYaoOutVO.setSignature1(yxHl7YzYaoPlanPO.getSignature1());
                    exeYaoOutVO.setSignature2(yxHl7YzYaoPlanPO.getSignature2());
                    exeYaoOutVO.setIsDiy(yxHl7YzYaoPlanPO.getIsDiy());
                    exeYaoOutVO.setDyAmount(yxHl7YzYaoPlanPO.getDyAmount());
                    exeYaoOutVO.setDyAmountUnit(yxHl7YzYaoPlanPO.getDyAmountUnit());
                    exeYaoOutVO.setCreatedTime(yxHl7YzYaoPlanPO.getCreatedTime());
                    exeYaoOutVO.setUpdatedBy(yxHl7YzYaoPlanPO.getUpdatedBy());
                    exeYaoOutVO.setCreatedBy(yxHl7YzYaoPlanPO.getCreatedBy());
                    if (null != yxHl7YzYaoPlanPO.getExeStatus() && (yxHl7YzYaoPlanPO.getExeStatus().equals("1") || yxHl7YzYaoPlanPO.equals("4"))) {
                        exeYaoOutVO.setEndTimestamp(yxHl7YzYaoPlanPO.getExeTime());
                        exeYaoOutVO.setStartTimestamp(yxHl7YzYaoPlanPO.getPlanTime());
                    } else {
                        exeYaoOutVO.setStartTimestamp(yxHl7YzYaoPlanPO.getExeTime());
                    }
                }
            });
            BigDecimal yaoUsedCounts = yaoPlanPoList.stream().filter(e -> null != e.getYtCount())
                    // 将user对象的mongey取出来map为Bigdecimal
                    .map(BHl7YzYaoPlan::getYtCount)
                    // 使用reduce聚合函数,实现累加器
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            double totalCounts = yaoPlanPoList.stream().filter(exeYaoShortOutVO -> exeYaoShortOutVO.getDyAmount() != null && "ml".equals(exeYaoShortOutVO.getDyAmountUnit())).mapToDouble(shortVo -> {
                if (StrUtil.isNotBlank(shortVo.getDyAmount())) {
                    return Double.parseDouble(shortVo.getDyAmount());
                }
                return 0;
            }).sum();
            //设置总量 实际用量
            exeYaoOutVO.setTotalCounts(totalCounts);
            exeYaoOutVO.setYaoUsedCounts(yaoUsedCounts);
            //药物列表 主药在前
            List<ExeYaoShortOutVO> yaoList = yaoPlanPoList.stream().sorted(Comparator.comparing(BHl7YzYaoPlan::getIsMaster).reversed()).map(ExeYaoShortOutVO::new).collect(Collectors.toList());
            exeYaoOutVO.setYaoList(yaoList);

            if (yaoPlanPoList.size() > 0) {
                exeYaoOutVO.setPlanTime(yaoPlanPoList.get(0).getPlanTime());
            }

            resultList.add(exeYaoOutVO);
        });


        List<ExeYaoOutVO> result = resultList;

        //根据执行状态条件筛选
        String exeStatus = queryVO.getExeStatus();
        ExeYaoStatusNewEnum exeYaoStatusEnum = ExeYaoStatusNewEnum.forValue(exeStatus);
        if (exeYaoStatusEnum != null) {

            result = result.stream().filter(
                    exeYaoOutVO -> {
                        if (null != exeYaoOutVO.getExeStatus()) {
                            return exeYaoOutVO.getExeStatus().equals(exeYaoStatusEnum.getStatusCode());
                        } else {
                            if (exeYaoStatusEnum.getStatusCode().equals("null")) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    }
            ).collect(Collectors.toList());
        }
        //根据排序字段排序
        ExeYaoSortFieldEnum sortFieldEnum = ExeYaoSortFieldEnum.forValue(sortName);
        if (sortFieldEnum != null) {
            switch (sortFieldEnum) {
                case PLAN_TIME:
                    //计划时间升序
                    result = result.stream().filter(e -> null != e.getPlanTime()).sorted(Comparator.comparing(ExeYaoOutVO::getPlanTime)).collect(Collectors.toList());
                    break;
                case EXE_TIME:
                    //执行时间升序
                    result = result.stream().filter(e -> null != e.getStartTimestamp()).sorted(Comparator.comparing(ExeYaoOutVO::getStartTimestamp, Comparator.nullsLast(LocalDateTime::compareTo))).collect(Collectors.toList());
                    break;
                case ST:
                    //st优先后再根据计划时间升序排序
                    result = result.stream().filter(e -> StringUtil.isNotEmpty(e.getRepeatIdent())).sorted(Comparator.comparing(ExeYaoOutVO::getRepeatIdent, Comparator.comparing(ExeYaoSortFieldEnum.ST.getSortName()::equalsIgnoreCase)).reversed().thenComparing(ExeYaoOutVO::getPlanTime)).collect(Collectors.toList());
                    break;
                default:
            }
        } else {
            result = resultList.stream().sorted(Comparator.comparing(ExeYaoOutVO::getYaoExeTime, Comparator.nullsLast(LocalDateTime::compareTo))).collect(Collectors.toList());
        }
//        List<LdeDevice> newlist=allForPage.stream().sorted(Comparator.comparing(LdeDevice::getIsAssociate, Comparator.nullsLast(String::compareTo))).collect(Collectors.toList())

        return result;
    }


    /**
     * 查询执行用药或出入量明细方法
     *
     * @param inputType      出入量类型
     * @param startTimeStr   开始时间
     * @param endTimeStr     结束时间
     * @param hospitalNumber 住院号
     * @param isIo           是否用于出入量模块（0 不是，1 是）
     * @return
     */
    private List<BHl7YzYaoPlan> selectYaoList(Integer inputType, String startTimeStr, String endTimeStr, String hospitalNumber, Integer isIo
            , String medicationName, String routeIdent, String conditionIdent, Integer iscare) {

        if (null == isIo) {
            return new ArrayList<>();
        }

        //执行用药主药
        List<BHl7YzYaoPlan> yaoPlanList = null;
        if (isIo == YES_NUMBER) {
            yaoPlanList = bHl7YzYaoPlanMapper.selectListByExeTimeQuery(hospitalNumber, null,
                    null, null, startTimeStr, endTimeStr, inputType, iscare, ChangeExeYaoStatusEnum.ZHI_XING.getStatusCode(), NO_NUMBER);
        } else {
            yaoPlanList = bHl7YzYaoPlanMapper.selectListByExeTimeQuery(hospitalNumber, medicationName, routeIdent, conditionIdent, startTimeStr, endTimeStr, inputType);
        }

        //出入量
        List<BHl7YzYaoPlan> yaoPlanList2 = bHl7YzYaoPlanMapper.selectListByExeTimeQuery(hospitalNumber, null,
                null, null, startTimeStr, endTimeStr, inputType, iscare, ChangeExeYaoStatusEnum.ZHI_XING.getStatusCode(), YES_NUMBER);
        //主要为空直接返回
        if (CollectionUtil.isEmpty(yaoPlanList) && CollectionUtil.isEmpty(yaoPlanList2)) {
            return new ArrayList<>();
        }
        List<HashMap<String, Object>> list = new ArrayList<>();
        yaoPlanList.forEach(yaoplan -> {
            HashMap<String, Object> item = new HashMap<>();
            item.put("groupid", yaoplan.getGroupId());
            item.put("plantime", yaoplan.getPlanTime());
            list.add(item);
        });

        //获取主要药gropid和plantime集合
        Set<String> groupIdList = yaoPlanList.stream().map(BHl7YzYaoPlan::getGroupId).collect(Collectors.toSet());
        Set<LocalDateTime> planTimeList = yaoPlanList.stream().map(BHl7YzYaoPlan::getPlanTime).collect(Collectors.toSet());
        //根据groupId和plantime查询主要相关的所有用药计划
        List<BHl7YzYaoPlan> yaoPlanListByGroup = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(yaoPlanList)) {
            //List<BHl7YzYaoPlan> listyao = bHl7YzYaoPlanMapper.selectListByGroupIdsAndExeTimeRange(groupIdList,planTimeList,hospitalNumber);
            List<BHl7YzYaoPlan> listyao = bHl7YzYaoPlanMapper.selectListByGroupIdsAndExeTimeRange(list, hospitalNumber);
            if (CollectionUtil.isNotEmpty(listyao)) {
                yaoPlanListByGroup.addAll(listyao);
            }
        }
        if (isIo == 1) {
            yaoPlanListByGroup.addAll(0, yaoPlanList2);
        }
        return yaoPlanListByGroup;
    }


    @Override
    public List<ExeYaoOiOutVO> countUsedByTimeRangeHospitalNumber(ExeYaoOiQueryVO queryVO) {
        String hospitalNumber = queryVO.getHospitalNumber();
        Long startTime = queryVO.getStartTime();
        Long endTime = queryVO.getEndTime();
        if (StrUtil.isBlank(hospitalNumber) || startTime == null || endTime == null) {
            throw new BizException("请输入住院号、开始和结束时间");
        }
        String startStr = DateUtil.formatDateTime(DateUtil.date(startTime));
        String endStr = DateUtil.formatDateTime(DateUtil.date(endTime));
        List<CountExeYaoDetailTimeRangeBO> usedDetailList = bHl7YzYaoPlanMapper.countDetailTimeRange(startStr, endStr, hospitalNumber, queryVO.getInputType());
        List<ExeYaoOiOutVO> result = usedDetailList.stream().map(ExeYaoOiOutVO::new).sorted(Comparator.comparing(ExeYaoOiOutVO::getExeTime)).collect(Collectors.toList());
        return result;
    }


    @Override
    public ExeYaoOutVO getYaoByMastId(Long id) {
        BHl7YzYaoPlan yxHl7YzYaoPlanPO = bHl7YzYaoPlanMapper.selectById(id);
        if (null == yxHl7YzYaoPlanPO) {
            throw new BizException("该组药不存在");
        }
        ExeYaoOutVO exeYaoOutVO = ConvertUtil.convert(yxHl7YzYaoPlanPO, ExeYaoOutVO.class);
        exeYaoOutVO.setYaoExeTime(yxHl7YzYaoPlanPO.getExeTime());
        exeYaoOutVO.setYaoStatus(yxHl7YzYaoPlanPO.getExeStatus());
        exeYaoOutVO.setMasterId(yxHl7YzYaoPlanPO.getId());

        exeYaoOutVO.setInputType(yxHl7YzYaoPlanPO.getInputType());
        exeYaoOutVO.setRemarks(yxHl7YzYaoPlanPO.getRemarks());
        exeYaoOutVO.setSignature1(yxHl7YzYaoPlanPO.getSignature1());
        exeYaoOutVO.setSignature2(yxHl7YzYaoPlanPO.getSignature2());
        exeYaoOutVO.setIsDiy(yxHl7YzYaoPlanPO.getIsDiy());
        exeYaoOutVO.setDyAmount(yxHl7YzYaoPlanPO.getDyAmount());
        exeYaoOutVO.setDyAmountUnit(yxHl7YzYaoPlanPO.getDyAmountUnit());
        exeYaoOutVO.setCreatedTime(yxHl7YzYaoPlanPO.getCreatedTime());
        exeYaoOutVO.setUpdatedBy(yxHl7YzYaoPlanPO.getUpdatedBy());
        exeYaoOutVO.setCreatedBy(yxHl7YzYaoPlanPO.getCreatedBy());
        if (null != yxHl7YzYaoPlanPO.getExeStatus() && (yxHl7YzYaoPlanPO.getExeStatus().equals("1") || yxHl7YzYaoPlanPO.equals("4"))) {
            exeYaoOutVO.setEndTimestamp(yxHl7YzYaoPlanPO.getExeTime());
            exeYaoOutVO.setStartTimestamp(yxHl7YzYaoPlanPO.getPlanTime());
        } else {
            exeYaoOutVO.setStartTimestamp(yxHl7YzYaoPlanPO.getExeTime());
        }
        exeYaoOutVO.setPlanTime(yxHl7YzYaoPlanPO.getPlanTime());
        List<BHl7YzYaoPlan> subList = bHl7YzYaoPlanMapper.selectSubList(yxHl7YzYaoPlanPO.getGroupId(), yxHl7YzYaoPlanPO.getHospitalNumber(), yxHl7YzYaoPlanPO.getPatientIdent(), yxHl7YzYaoPlanPO.getPlanTime());
        if (CollectionUtil.isNotEmpty(subList)) {
            List<String> medications = subList.stream().sorted(Comparator.comparing(BHl7YzYaoPlan::getIsMaster).reversed()).map(BHl7YzYaoPlan::getMedication).collect(Collectors.toList());
            //药名由在同一组下的药名拼接组成
            String medicationName = String.join(MED_DELIMITER, medications);
            exeYaoOutVO.setMedicationName(medicationName);
            BigDecimal yaoUsedCounts = subList.stream().filter(e -> null != e.getYtCount())
                    // 将user对象的mongey取出来map为Bigdecimal
                    .map(BHl7YzYaoPlan::getYtCount)
                    // 使用reduce聚合函数,实现累加器
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            double totalCounts = subList.stream().filter(exeYaoShortOutVO -> exeYaoShortOutVO.getDyAmount() != null && "ml".equals(exeYaoShortOutVO.getDyAmountUnit())).mapToDouble(shortVo -> {
                if (StrUtil.isNotBlank(shortVo.getDyAmount())) {
                    return Double.parseDouble(shortVo.getDyAmount());
                }
                return 0;
            }).sum();
            //设置总量 实际用量
            exeYaoOutVO.setTotalCounts(totalCounts);
            exeYaoOutVO.setYaoUsedCounts(yaoUsedCounts);
            List<ExeYaoShortOutVO> yaoList = subList.stream().sorted(Comparator.comparing(BHl7YzYaoPlan::getIsMaster).reversed()).map(ExeYaoShortOutVO::new).collect(Collectors.toList());
            //药物列表 主药在前
            exeYaoOutVO.setYaoList(yaoList);
        }
        return exeYaoOutVO;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addExeYao(ExeYaoInVO inVO) {
        DefUserInfoResultVO defUserInfoResultVO = oauthUserBiz.getUserById(ContextUtil.getUserId());

        List<YaoPlanInVO> yaoList = inVO.getYaoList();
        if (CollectionUtil.isEmpty(yaoList)) {
            throw new BizException("药物列表不能为空");
        }
        String operaType = inVO.getOperaType();
        ExeYaoOperaTypeEnum typeEnum = ExeYaoOperaTypeEnum.forValue(operaType);
        if (typeEnum == null) {
            throw new BizException("请输入正确的操作指令");
        }
        //用于药物分组的标识
        String groupId = UUID.randomUUID().toString(true);
        List<BHl7YzYaoPlan> yaoPlanPOList = yaoList.stream().map(yaoPlanInVO -> {
            BHl7YzYaoPlan yaoPlanPO = new BHl7YzYaoPlan();
            yaoPlanPO.setPatientIdent(inVO.getPatientIdent());
            yaoPlanPO.setHospitalNumber(inVO.getHospitalNumber());
            yaoPlanPO.setRepeatIdent(inVO.getRepeatIdent());
            yaoPlanPO.setRouteIdent(inVO.getRouteIdent());
            yaoPlanPO.setWayIdent(inVO.getWayIdent());
            yaoPlanPO.setChannelIdent(inVO.getChannelIdent());
            yaoPlanPO.setGroupId(groupId);
            if (inVO.getPlanTime() != null) {
                yaoPlanPO.setPlanTime(PDateUtils.getDateTimeOfTimestamp(inVO.getPlanTime()));
            }
            yaoPlanPO.setIsDiy(YES_NUMBER);
            yaoPlanPO.setMedication(yaoPlanInVO.getMedication());
            yaoPlanPO.setMedicationIdent(yaoPlanInVO.getMedicationIdent());
            yaoPlanPO.setSpec(yaoPlanInVO.getSpec());
            yaoPlanPO.setAmount(yaoPlanInVO.getAmount());
            yaoPlanPO.setAmountUnit(yaoPlanInVO.getAmountUnit());
            //2022.4.26 xpx 修改
            yaoPlanPO.setDyAmount(yaoPlanInVO.getDyAmount());
            yaoPlanPO.setDyAmountUnit(yaoPlanInVO.getDyAmountUnit());

            yaoPlanPO.setYtCount(yaoPlanInVO.getYtCount());
            yaoPlanPO.setSignature1(inVO.getSignature1());
            yaoPlanPO.setSignature2(inVO.getSignature2());
            yaoPlanPO.setRemarks(inVO.getRemarks());
            yaoPlanPO.setExeStatus(inVO.getExeStatus());
            yaoPlanPO.setExeTime(PDateUtils.getDateTimeOfTimestamp(inVO.getExeTime()));
            yaoPlanPO.setIsFromio(0);
            yaoPlanPO.setInputType(inVO.getInputType());
            yaoPlanPO.setPlanStatusIdent("NW");
            yaoPlanPO.setCreatedBy(ContextUtil.getUserId());
            yaoPlanPO.setUpdatedBy(ContextUtil.getUserId());

            yaoPlanPO.setOperatorGh(defUserInfoResultVO.getUsername());
            if (yaoPlanPO.getInputType() == 7) {
                BigDecimal count = new BigDecimal(yaoPlanPO.getDyAmount());
                BigDecimal def1 = new BigDecimal(200);
                BigDecimal def2 = new BigDecimal(20);
                if (yaoPlanPO.getDyAmountUnit().equals("U")) {
                    if (yaoPlanPO.getMedication().equals("全血") || yaoPlanPO.getMedication().equals("去白细胞悬浮红细胞") || yaoPlanPO.getMedication().equals("悬浮红细胞")) {
                        yaoPlanPO.setYtCount(count.multiply(def1));
                    }
                    if (yaoPlanPO.getMedication().equals("血浆") || yaoPlanPO.getMedication().equals("冰冻血浆") || yaoPlanPO.getMedication().equals("异体血浆")) {
                        yaoPlanPO.setYtCount(count.multiply(def1));
                    }
                    if (yaoPlanPO.getMedication().equals("冷沉淀")) {
                        yaoPlanPO.setYtCount(count.multiply(def2));
                    }
                    if (yaoPlanPO.getMedication().contains("血小板")) {
                        yaoPlanPO.setYtCount(count.multiply(def2));
                    }
                } else if (yaoPlanPO.getDyAmountUnit().equals("ml")) {
                    yaoPlanPO.setYtCount(count);
                }
            }
            return yaoPlanPO;
        }).collect(Collectors.toList());
        //默认第一个为主药
        yaoPlanPOList.get(0).setIsMaster(YES_NUMBER);
        //插入数据库
//        yaoPlanService.saveBatch(yaoPlanPOList);

        for (int i = 0; i < yaoPlanPOList.size(); i++) {
            BHl7YzYaoPlan hl7YzYaoPlanPO = yaoPlanPOList.get(i);
            bHl7YzYaoPlanMapper.insert(hl7YzYaoPlanPO);

            BIoRecord yxIoRecordPO = new BIoRecord();
//            yxIoRecordPO.setCreateBy("his");
//            yxIoRecordPO.setUpdateBy("his");
            yxIoRecordPO.setHospitalNumber(hl7YzYaoPlanPO.getHospitalNumber());
            yxIoRecordPO.setPatientIdent(hl7YzYaoPlanPO.getPatientIdent());
            yxIoRecordPO.setIsType(1);
            yxIoRecordPO.setItemCode(StringCommon.getItemCode(hl7YzYaoPlanPO.getInputType()));
            yxIoRecordPO.setTime(StringCommon.getTimeByExeTime(PDateUtils.LocalDateTimeToDate(hl7YzYaoPlanPO.getExeTime())));
            ZoneId zone = ZoneId.systemDefault();
            LocalDateTime localDateTime = hl7YzYaoPlanPO.getExeTime();
            yxIoRecordPO.setRealTime(localDateTime);
            yxIoRecordPO.setGroupId(hl7YzYaoPlanPO.getGroupId());
            if (null != hl7YzYaoPlanPO.getYtCount()) {
                yxIoRecordPO.setIoValue(hl7YzYaoPlanPO.getYtCount().toString());
            } else {
                yxIoRecordPO.setIoValue("0");
            }
            if (inVO.getInputType() == -1) {
                yxIoRecordPO.setIsYaoSum(0);
            } else {
                yxIoRecordPO.setIsYaoSum(1);
            }
            yxIoRecordPO.setYaoId(hl7YzYaoPlanPO.getId());
            yxIoRecordPO.setModelCode("crl-in");
            yxIoRecordPO.setSource("bulu");
            yxIoRecordPO.setMedication(hl7YzYaoPlanPO.getMedication());
            yxIoRecordPO.setDyAmount(hl7YzYaoPlanPO.getDyAmount());
            yxIoRecordPO.setDyAmountUnit(hl7YzYaoPlanPO.getDyAmountUnit());
            yxIoRecordPO.setIsMaster(hl7YzYaoPlanPO.getIsMaster());
            yxIoRecordPO.setPlanTime(hl7YzYaoPlanPO.getPlanTime());
            yxIoRecordPO.setSpec(hl7YzYaoPlanPO.getSpec());
            bIoRecordMapper.insert(yxIoRecordPO);
        }


        //用药事件记录
        if (typeEnum.equals(ExeYaoOperaTypeEnum.EXE_NOW)) {
            Integer speed = inVO.getSpeed();
            Integer totalYtCount = inVO.getTotalYtCount();
//            if (speed == null || speed <= 0 || totalYtCount == null) {
            if (totalYtCount == null) {
                throw new BizException(" 液体总量不能为空且不能为0");
            }
            Long exeTime = inVO.getExeTime();
            if (exeTime == null) {
                throw new BizException("执行时间不能为空");
            }
            //用主药的id进行执行用药的关联
            BExeYaoEvent eventPO = new BExeYaoEvent();
            eventPO.setPatientIdent(inVO.getPatientIdent());
            eventPO.setHospitalNumber(inVO.getHospitalNumber());
            eventPO.setGroupId(groupId);
            eventPO.setEventType(ExeYaoEventTypeEnum.START.getEventType());
            eventPO.setEventTime(PDateUtils.getDateTimeOfTimestamp(exeTime));
            eventPO.setSpeed(inVO.getSpeed());
            eventPO.setCurrentSpeed(inVO.getSpeed());
            bExeYaoEventMapper.insert(eventPO);

        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateExeYao(UpdateExeYaoInVO inVO) {
        //修改
        List<YaoPlanInVO> yaoList = inVO.getYaoList();
        if (CollectionUtil.isEmpty(yaoList)) {
            throw new BizException("请输入用药的数据集合");
        }
        //先删除所有之前的用药
//        yaoPlanService.updateDeleteStatusByGroupId(inVO.getGroupId(), YES_NUMBER);
        //添加新的用药

        LocalDateTime oldTime = null;
        for (int i = 0; i < yaoList.size(); i++) {
            YaoPlanInVO yaoPlanInVO = yaoList.get(i);
            BHl7YzYaoPlan yaoPlanPO = handleYaoPlan(yaoPlanInVO, inVO);
            if (yaoPlanPO.getId() != null) {
                if (null == oldTime) {
                    BHl7YzYaoPlan yao = bHl7YzYaoPlanMapper.selectById(yaoPlanPO.getId());
                    if(null!=yao){
                        oldTime = yao.getExeTime();
                    }

                }


                if (null != SecurityUtil.checkRecordAuth(yaoPlanPO.getCreatedBy(), yaoPlanPO.getUpdatedBy(), ContextUtil.getUserId())) {
                    throw new BizException(SecurityUtil.checkRecordAuth(yaoPlanPO.getCreatedBy(), yaoPlanPO.getUpdatedBy(), ContextUtil.getUserId()));
                }
                //修改
                if (i == 0) {
                    yaoPlanPO.setIsMaster(YES_NUMBER);
                } else {
                    yaoPlanPO.setIsMaster(NO_NUMBER);
                }
                yaoPlanPO.setUpdatedBy(ContextUtil.getUserId());
                bHl7YzYaoPlanService.updateById(yaoPlanPO);

                //修改对应出入量的数据
                LambdaUpdateWrapper<BIoRecord> ioUpdateWrapper = new LambdaUpdateWrapper<>();
                if (inVO.getInputType() == -1) {
                    ioUpdateWrapper.set(BIoRecord::getIsYaoSum, 0);
                } else if (yaoPlanPO.getExeStatus().equals(1)) {
                    ioUpdateWrapper.set(BIoRecord::getIsYaoSum, 1);
                } else if (yaoPlanPO.getExeStatus().equals("0")) {
                    ioUpdateWrapper.set(BIoRecord::getIsYaoSum, 0);
                }

//                ioUpdateWrapper.set(BIoRecord::getRealTime,yaoPlanPO.getExeTime());
                ioUpdateWrapper.set(BIoRecord::getCreatedBy, yaoPlanPO.getCreatedBy());
                ioUpdateWrapper.set(BIoRecord::getUpdatedBy, yaoPlanPO.getUpdatedBy());
                ioUpdateWrapper.set(BIoRecord::getIoValue, yaoPlanPO.getYtCount().toPlainString());
                ioUpdateWrapper.set(BIoRecord::getMedication, yaoPlanPO.getMedication());
                ioUpdateWrapper.set(BIoRecord::getDyAmount, yaoPlanPO.getDyAmount());
                ioUpdateWrapper.set(BIoRecord::getDyAmountUnit, yaoPlanPO.getDyAmountUnit());
                ioUpdateWrapper.set(BIoRecord::getItemCode, StringCommon.getItemCode(yaoPlanPO.getInputType()));
                if (null != yaoPlanPO.getIsDiy()) {
                    if (yaoPlanPO.getIsDiy() == 0) {    //his
                        ioUpdateWrapper.set(BIoRecord::getSource, "his");
                    } else if (yaoPlanPO.getIsDiy() == 1) { //补录
                        ioUpdateWrapper.set(BIoRecord::getSource, "bulu");
                    }
                }


                if (null != yaoPlanPO.getExeTime()) {
//                    LocalDateTime time= StringCommon.getTimeByExeTime(yaoPlanPO.getExeTime());

                    ioUpdateWrapper.set(BIoRecord::getRealTime, yaoPlanPO.getExeTime());
                    LocalDateTime localtime = yaoPlanPO.getExeTime();

                    ioUpdateWrapper.set(BIoRecord::getTime, localtime);
                }

                ioUpdateWrapper.set(BIoRecord::getIsMaster, yaoPlanPO.getIsMaster());
                ioUpdateWrapper.set(BIoRecord::getPlanTime, yaoPlanPO.getPlanTime());
                ioUpdateWrapper.set(BIoRecord::getSpec, yaoPlanPO.getSpec());
                ioUpdateWrapper.eq(BIoRecord::getYaoId, yaoPlanPO.getId());
                bIoRecordMapper.update(null, ioUpdateWrapper);
            } else {
                //新增
                if (null == yaoPlanPO.getExeTime()) {
                    throw new BizException("执行时间不能为空");
                }
                if (i == 0) {
                    yaoPlanPO.setIsMaster(YES_NUMBER);
                } else {
                    yaoPlanPO.setIsMaster(NO_NUMBER);
                }
                yaoPlanPO.setIsDiy(YES_NUMBER);
                yaoPlanPO.setInputType(inVO.getInputType());
                yaoPlanPO.setCreatedBy(ContextUtil.getUserId());
                yaoPlanPO.setUpdatedBy(ContextUtil.getUserId());
                bHl7YzYaoPlanService.save(yaoPlanPO);


                BIoRecord yxIoRecordPO = new BIoRecord();
                //          yxIoRecordPO.setCreateBy("his");
                //          yxIoRecordPO.setUpdateBy("his");
                yxIoRecordPO.setHospitalNumber(yaoPlanPO.getHospitalNumber());
                yxIoRecordPO.setPatientIdent(yaoPlanPO.getPatientIdent());
                yxIoRecordPO.setIsType(1);
                yxIoRecordPO.setItemCode(StringCommon.getItemCode(yaoPlanPO.getInputType()));
                yxIoRecordPO.setTime(yaoPlanPO.getExeTime());

                ZoneId zone = ZoneId.systemDefault();
                LocalDateTime localDateTime = yaoPlanPO.getExeTime();
                yxIoRecordPO.setRealTime(localDateTime);
                yxIoRecordPO.setGroupId(yaoPlanPO.getGroupId());
                if (null != yaoPlanPO.getYtCount()) {
                    yxIoRecordPO.setIoValue(yaoPlanPO.getYtCount().toString());
                } else {
                    yxIoRecordPO.setIoValue("0");
                }
                if (inVO.getInputType() == -1) {
                    yxIoRecordPO.setIsYaoSum(0);
                } else if (yaoPlanPO.getExeStatus().equals("1")) {
                    yxIoRecordPO.setIsYaoSum(1);
                } else {
                    yxIoRecordPO.setIsYaoSum(0);
                }

                yxIoRecordPO.setYaoId(yaoPlanPO.getId());
                yxIoRecordPO.setModelCode("crl-in");
                yxIoRecordPO.setSource("bulu");
                yxIoRecordPO.setMedication(yaoPlanPO.getMedication());
                yxIoRecordPO.setDyAmount(yaoPlanPO.getDyAmount());
                yxIoRecordPO.setDyAmountUnit(yaoPlanPO.getDyAmountUnit());
                yxIoRecordPO.setIsMaster(yaoPlanPO.getIsMaster());
                yxIoRecordPO.setPlanTime(yaoPlanPO.getPlanTime());
                yxIoRecordPO.setSpec(yaoPlanPO.getSpec());
                bIoRecordMapper.insert(yxIoRecordPO);
            }
        }
    }

    private BHl7YzYaoPlan handleYaoPlan(YaoPlanInVO yaoPlanInVO, UpdateExeYaoInVO inVO) {
        BHl7YzYaoPlan yaoPlanPO = new BHl7YzYaoPlan();
        BeanUtil.copyProperties(yaoPlanInVO, yaoPlanPO);
        yaoPlanPO.setPatientIdent(inVO.getPatientIdent());
        yaoPlanPO.setHospitalNumber(inVO.getHospitalNumber());
        yaoPlanPO.setGroupId(inVO.getGroupId());
        yaoPlanPO.setPlanTime(PDateUtils.getDateTimeOfTimestamp(inVO.getPlanTime()));
        yaoPlanPO.setRouteIdent(inVO.getRouteIdent());
        yaoPlanPO.setWayIdent(inVO.getWayIdent());
        yaoPlanPO.setChannelIdent(inVO.getChannelIdent());
        yaoPlanPO.setDoctorName(inVO.getDoctorName());
        yaoPlanPO.setRepeatIdent(inVO.getRepeatIdent());
        if (null != inVO.getOperaTime()) {
            yaoPlanPO.setOperaTime(PDateUtils.getDateTimeOfTimestamp(inVO.getOperaTime()));
        }

        yaoPlanPO.setIsMaster(NO_NUMBER);
        yaoPlanPO.setSignature1(inVO.getSignature1());
        yaoPlanPO.setSignature2(inVO.getSignature2());

        //这个状态值his那边前期没给 没同步到 暂时先注释
//        yaoPlanPO.setPlanStatusIdent("NW");

        yaoPlanPO.setExeTime(inVO.getExeTime());
        yaoPlanPO.setRemarks(inVO.getRemarks());
        yaoPlanPO.setExeStatus(inVO.getExeStatus());
        yaoPlanPO.setInputType(inVO.getInputType());
        return yaoPlanPO;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteExeYao(DelExeYaoInVO inVO) {
        DefUserInfoResultVO defUserInfoResultVO = oauthUserBiz.getUserById(ContextUtil.getUserId());

        String groupId = inVO.getGroupId();
        String medicationName = inVO.getMedicationName();
        String hospitalNumber = inVO.getHospitalNumber();
        if (StrUtil.isBlank(groupId)) {
            throw new BizException("请输入用药分组id");
        }
        if (StrUtil.isBlank(medicationName)) {
            throw new BizException("请输入用药名称");
        }
        if (StrUtil.isBlank(hospitalNumber)) {
            throw new BizException("请输入住院号");
        }

        List<BHl7YzYaoPlan> yaoPlanPOList = bHl7YzYaoPlanService.getYaoPlanListByGroupId(inVO.getGroupId());
        if (CollectionUtil.isNotEmpty(yaoPlanPOList)) {
            if (null != SecurityUtil.checkRecordAuth(yaoPlanPOList.get(0).getCreatedBy(), yaoPlanPOList.get(0).getUpdatedBy(), ContextUtil.getUserId())) {
                throw new BizException(SecurityUtil.checkRecordAuth(yaoPlanPOList.get(0).getCreatedBy(), yaoPlanPOList.get(0).getUpdatedBy(), ContextUtil.getUserId()));
            }

        }

        //删除对应的主用药事件
        bExeYaoEventMapper.deleteByGroupId(groupId);

        //更改删除状态 yes
        bHl7YzYaoPlanService.updateDeleteStatusByGroupId(groupId, YES_NUMBER);

        //根据组号删除对应的出入量
        bIoRecordMapper.delete(new QueryWrapper<BIoRecord>().eq("group_id", groupId));

        //插入删除记录
        String nickName = defUserInfoResultVO.getUsername();
        BExeYaoRevokeRecord revokeRecordPO = new BExeYaoRevokeRecord();
        revokeRecordPO.setMedicationName(medicationName);
        revokeRecordPO.setGroupId(groupId);
        revokeRecordPO.setDelTime(LocalDateTime.now());
        revokeRecordPO.setOperaName(nickName);
        revokeRecordPO.setDelReason(inVO.getDelReason());
        revokeRecordPO.setHospitalNumber(hospitalNumber);
        bExeYaoRevokeRecordMapper.insert(revokeRecordPO);

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMaster(Long id, Long oldMasterId) {

        BHl7YzYaoPlan yaoPlanPO = bHl7YzYaoPlanMapper.selectById(id);
        BHl7YzYaoPlan yaoPlanPOold = bHl7YzYaoPlanMapper.selectById(oldMasterId);
        if (null != id&&null!=yaoPlanPO) {
            if (null != SecurityUtil.checkRecordAuth(yaoPlanPO.getCreatedBy(), yaoPlanPO.getUpdatedBy(), ContextUtil.getUserId())) {
                throw new BizException(SecurityUtil.checkRecordAuth(yaoPlanPO.getCreatedBy(), yaoPlanPO.getUpdatedBy(), ContextUtil.getUserId()));
            }
        }
        if (null == yaoPlanPO) {
            throw new BizException("修改药品不存在");
        }
        if (null == yaoPlanPOold) {
            throw new BizException("原药品不存在");
        }
        yaoPlanPOold.setIsMaster(0);
        yaoPlanPO.setIsMaster(1);
        List<BHl7YzYaoPlan> updatas = new ArrayList<>();
        updatas.add(yaoPlanPOold);
        updatas.add(yaoPlanPO);

        bHl7YzYaoPlanMapper.updateById(updatas);


        //出入量同步执行用药 的是否主药逻辑
        LambdaUpdateWrapper<BIoRecord> ioUpdateWrapperOld = new LambdaUpdateWrapper<>();

        ioUpdateWrapperOld.set(BIoRecord::getIsMaster, yaoPlanPOold.getIsMaster());
        ioUpdateWrapperOld.eq(BIoRecord::getYaoId, yaoPlanPOold.getId());
        bIoRecordMapper.update(null, ioUpdateWrapperOld);

        LambdaUpdateWrapper<BIoRecord> ioUpdateWrapperNew = new LambdaUpdateWrapper<>();

        ioUpdateWrapperNew.set(BIoRecord::getIsMaster, yaoPlanPO.getIsMaster());
        ioUpdateWrapperNew.eq(BIoRecord::getYaoId, yaoPlanPO.getId());
        bIoRecordMapper.update(null, ioUpdateWrapperNew);

        return true;
    }

    @Override
    public List<RevokeRecordYaoOutVO> selectRevokeRecords(String hospitalNumber) {
        Calendar calendar = Calendar.getInstance();
        Date endDate = calendar.getTime();
        //当前时间往前推24小时
        calendar.add(Calendar.HOUR_OF_DAY, -24);
        Date startDate = calendar.getTime();
        String startDateStr = DateUtil.formatDateTime(startDate);
        String endDateStr = DateUtil.formatDateTime(endDate);

        LambdaQueryWrapper<BExeYaoRevokeRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(hospitalNumber), BExeYaoRevokeRecord::getHospitalNumber, hospitalNumber)
                .gt(BExeYaoRevokeRecord::getDelTime, startDateStr).lt(BExeYaoRevokeRecord::getDelTime, endDateStr);
        List<BExeYaoRevokeRecord> recordPOList = bExeYaoRevokeRecordMapper.selectList(queryWrapper);
        List<RevokeRecordYaoOutVO> result = recordPOList.stream().map(RevokeRecordYaoOutVO::new).collect(Collectors.toList());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void revokeDeleteExeYao(List<RevokeInVO> records) {
        if (CollectionUtil.isEmpty(records)) {
            throw new BizException("请输入要撤销的数据集合");
        }
        //更改删除状态 no
        List<String> groupIdList = records.stream().map(RevokeInVO::getGroupId).collect(Collectors.toList());
        groupIdList.forEach(groupId -> bHl7YzYaoPlanService.updateDeleteStatusByGroupId(groupId, NO_NUMBER));

        //删除撤销记录
        List<Long> recordId = records.stream().map(RevokeInVO::getRecordId).collect(Collectors.toList());
        bExeYaoRevokeRecordMapper.deleteByIds(recordId);
    }

}


